package com.xtayfjpk.security.jsse;

import java.io.OutputStream;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

/**
 * 	-Djavax.net.ssl.keyStore=clientKeys
	-Djavax.net.ssl.keyStorePassword=password
	-Djavax.net.ssl.trustStore=clientTrust
	-Djavax.net.ssl.trustStorePassword=password
 * @author zj
 *
 */
public class SimpleSSLClient {
	
	public static void main(String[] args) throws Exception {
		SSLContext context = SSLContext.getInstance("SSL");
		String keyStorePassword = "password";
		KeyStore clientKeys = SimpleSSLServer.getKeyStore("jim.keystore", "jks", keyStorePassword);
		KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
		String privateKeyPassword = "xtayfjpk";
		keyManagerFactory.init(clientKeys, privateKeyPassword.toCharArray());
		
		TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		String trustStorePassword = "password";
		KeyStore serverTrustKeys = SimpleSSLServer.getKeyStore("clientTrust", "jks", trustStorePassword);
		trustManagerFactory.init(serverTrustKeys);
		System.out.println(keyManagerFactory.getKeyManagers().length);
		context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
		
		
		
		
		
		
		SSLSocketFactory factory = (SSLSocketFactory) context.getSocketFactory();
		
		//SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
		
		String host = "127.0.0.1";
		SSLSocket socket = (SSLSocket) factory.createSocket(host, 9999);
		
		System.out.println(socket.isConnected());
		//socket.startHandshake();
		OutputStream outputStream = socket.getOutputStream();
		outputStream.write("zhangjin".getBytes());
		outputStream.flush();
		outputStream.close();
		socket.close();
		
	}
}
